import plugin from '../../../lib/plugins/plugin.js';
import fs from 'fs';
import path from 'path';

const dataPath = 'plugins/hl-impart-plugin/data';

if (!fs.existsSync(dataPath)) {
  fs.mkdirSync(dataPath, { recursive: true });
}

const defaultCooldown = 30000; // 冷却时间30秒
const duelCooldown = 30000; // 决斗冷却时间30秒

export default class NiuNiuPlugin extends plugin {
  constructor() {
    super({
      name: '轻量版impart',
      dsc: 'HL',
      event: 'message',
      priority: 1000,
      rule: [
        { 
          reg: '^#?生成牛牛$', 
          fnc: 'generateNiuNiu'
        },
        { 
          reg: '^#?kill牛牛$', 
          fnc: 'resetNiuNiu'
        },
        { 
          reg: '^#?(打胶|开导)$', 
          fnc: 'increaseLength'
        },
        { 
          reg: '^#?嗦牛牛(?: @(.+))?$', 
          fnc: 'suckNiuNiu' 
        },
        { 
          reg: '^#?决斗(?: @(.+))?$', 
          fnc: 'duel' 
        },
        { 
          reg: '^#?查看牛牛(?: @(.+))?$', 
          fnc: 'checkLength' 
        },
        { 
          reg: '^#?牛牛排行榜$', 
          fnc: 'leaderboard' 
        },
        { 
          reg: '^#?yp改名(.+)$', 
          fnc: 'changeName' 
        }  
      ]
    });
  }

  async getNickname(userId) {
    const userDataFile = path.join(dataPath, `${userId}.json`);
    if (fs.existsSync(userDataFile)) {
      const data = JSON.parse(fs.readFileSync(userDataFile));
      return data.name || '未设置名称';  
    } else {
      return '未设置名称';
    }
  }

  getMentionedInfo() {
    const mention = this.e.message.find(msg => msg.type === 'at');
    return mention ? mention.qq : null;
  }

  async generateNiuNiu(e) {
    const userId = e.user_id;
    const userDataFile = path.join(dataPath, `${userId}.json`);

    if (fs.existsSync(userDataFile)) {
      e.reply('你已经生成了牛牛了哦！如果想重新开始就发送【kill牛牛】');
      return;
    }

    const length = (Math.random() * 24 + 1).toFixed(1);
    const data = { name: '未设置名称', length: parseFloat(length), cooldown: 0, duelCooldown: 0, suckCooldown: 0, increaseCount: 0, selfSuckCount: 0, othersSuckCount: 0 };
    fs.writeFileSync(userDataFile, JSON.stringify(data));

    e.reply(`你的牛牛长出来啦！长度为${length}cm`);
  }

  async resetNiuNiu(e) {
    const userId = e.user_id;
    const userDataFile = path.join(dataPath, `${userId}.json`);

    if (fs.existsSync(userDataFile)) {
      fs.unlinkSync(userDataFile);
      this.generateNiuNiu(e);
    } else {
      e.reply('你还没有牛牛！哪有牛牛kill！请发送【生成牛牛】来生成牛牛！');
    }
  }

  async increaseLength(e) {
    const userId = e.user_id;
    const userDataFile = path.join(dataPath, `${userId}.json`);

    if (!fs.existsSync(userDataFile)) {
      e.reply('你还没有牛牛！请先生成牛牛！发送‘生成牛牛’即可生成哦！');
      return;
    }

    const data = JSON.parse(fs.readFileSync(userDataFile));
    const currentTime = Date.now();

    if (currentTime < data.cooldown) {
      const remainingTime = ((data.cooldown - currentTime) / 1000).toFixed(1);
      e.reply(`导不动了...在冷却中呢，请稍后再试！剩余时间：${remainingTime}秒`);
      return;
    }

    const increment = (Math.random() * 9 + 1).toFixed(1);
    data.length += parseFloat(increment);
    data.increaseCount = (data.increaseCount || 0) + 1;
    data.cooldown = currentTime + defaultCooldown;
    fs.writeFileSync(userDataFile, JSON.stringify(data));

    e.reply(`经历了一夜的奋战 你的牛牛成功增加了${increment}cm`);
  }

  async suckNiuNiu(e) {
    const targetId = this.getMentionedInfo();
    const userId = e.user_id;
    const userDataFile = path.join(dataPath, `${userId}.json`);
    const targetDataFile = targetId ? path.join(dataPath, `${targetId}.json`) : null;

    if (targetId === null) {
      e.reply('？？请艾特要嗦牛牛的玩家');
      return;
    }

    if (!fs.existsSync(userDataFile)) {
      e.reply('你还没有牛牛！请先生成牛牛！');
      return;
    }

    if (!fs.existsSync(targetDataFile)) {
      e.reply(targetId !== userId ? '该玩家还没有牛牛哦！请让该玩家发送【生成牛牛】再来决斗吧！' : '你还没有牛牛！请先生成牛牛！');
      return;
    }

    const data = JSON.parse(fs.readFileSync(userDataFile));
    const targetData = JSON.parse(fs.readFileSync(targetDataFile));
    const currentTime = Date.now();

    if (currentTime < data.suckCooldown) {
      const remainingTime = ((data.suckCooldown - currentTime) / 1000).toFixed(1);
      e.reply(`指令冷却中，请稍后再试！剩余时间：${remainingTime}秒`);
      return;
    }

    if (targetId !== userId) {
      const increment = (Math.random() * 9 + 1).toFixed(1);
      targetData.length += parseFloat(increment);
      data.othersSuckCount = (data.othersSuckCount || 0) + 1;
      fs.writeFileSync(targetDataFile, JSON.stringify(targetData));
      e.reply(`你激情满满的给 ${await this.getNickname(targetId)} 嗦了好久，该玩家增加了${increment}cm`);
    } else {
      const success = Math.random() > 0.5;
      if (success) {
        const increment = (Math.random() * 9 + 1).toFixed(1);
        data.length += parseFloat(increment);
        data.selfSuckCount = (data.selfSuckCount || 0) + 1;
        e.reply(`你居然嗦自己的牛牛！你的牛牛很舒服，并增加了${increment}cm`);
      } else {
        const decrement = (Math.random() * 4 + 1).toFixed(1);
        data.length -= parseFloat(decrement);
        e.reply(`你用尽全身力气终于嗦到了自己的牛牛，但你的牛牛好像不满足并减少了${decrement}cm`);
      }
    }

    data.suckCooldown = currentTime + defaultCooldown;
    fs.writeFileSync(userDataFile, JSON.stringify(data));
  }

  async duel(e) {
    const targetId = this.getMentionedInfo();
    const userId = e.user_id;
    const userDataFile = path.join(dataPath, `${userId}.json`);
    const targetDataFile = targetId ? path.join(dataPath, `${targetId}.json`) : null;

    if (targetId === null) {
      e.reply('？？请艾特要决斗的玩家');
      return;
    }

    if (targetId === userId) {
      e.reply('不能和自己决斗！');
      return;
    }

    if (!fs.existsSync(userDataFile) || !fs.existsSync(targetDataFile)) {
      e.reply('双方都需要生成牛牛才能决斗！');
      return;
    }

    const userData = JSON.parse(fs.readFileSync(userDataFile));
    const targetData = JSON.parse(fs.readFileSync(targetDataFile));
    const currentTime = Date.now();

    if (currentTime < userData.duelCooldown) {
      const remainingTime = ((userData.duelCooldown - currentTime) / 1000).toFixed(1);
      e.reply(`指令冷却中，请稍后再试！剩余时间：${remainingTime}秒`);
      return;
    }

    const result = Math.random() > 0.5;
    const increment = (Math.random() * 9 + 1).toFixed(1);
    if (result) {
      userData.length += parseFloat(increment);
      e.reply(`你与 ${await this.getNickname(targetId)} 战斗了三天三夜，你的牛牛增加了${increment}cm`);
    } else {
      userData.length -= parseFloat(increment);
      e.reply(`你与 ${await this.getNickname(targetId)} 战斗了三天三夜，你的牛牛减少了${increment}cm`);
    }

    userData.duelCooldown = currentTime + duelCooldown;
    fs.writeFileSync(userDataFile, JSON.stringify(userData));
  }

  async checkLength(e) {
    const targetId = this.getMentionedInfo();
    const userId = targetId || e.user_id;
    const userDataFile = path.join(dataPath, `${userId}.json`);

    if (!fs.existsSync(userDataFile)) {
      e.reply('该玩家还没有牛牛哦！请让该玩家发送【生成牛牛】生成牛牛吧！');
      return;
    }

    const data = JSON.parse(fs.readFileSync(userDataFile));
    e.reply(`${await this.getNickname(userId)} 的牛牛长度为 ${data.length}cm`);
  }

  async leaderboard(e) {
    const allDataFiles = fs.readdirSync(dataPath).filter(file => file.endsWith('.json'));
    const allData = allDataFiles.map(file => JSON.parse(fs.readFileSync(path.join(dataPath, file))));
  
    
    allData.sort((a, b) => b.length - a.length);
  
    
    const forwardNodes = allData.map((data, index) => ({
      user_id: e.user_id,
      nickname: data.name || '未命名',
      message: [
        `-------------`,
        `🏆排名 ${index + 1}`,
        `👤玩家: 【${data.name || '未命名'}】`,
        `🐂牛牛长度: ${data.length} cm`,
        `🥰嗦别人次数: ${data.othersSuckCount || 0}`,
        `😋嗦自己次数: ${data.selfSuckCount || 0}`,
        `🥵被别人嗦次数: ${data.suckedByOthersCount || 0}`,
        `-------------`,
      ].join('\n')
    }));
  
    if (forwardNodes.length === 0) {
      e.reply('当前没有数据可以显示排行榜。');
      return;
    }
  
    try {
      
      const forwardMessage = await Bot.makeForwardMsg(forwardNodes);
      await e.reply(forwardMessage);
    } catch (error) {
      console.error('发送排行榜出错:', error);
      e.reply('排行榜发送失败');
    }
  }
  

  async changeName(e) {
    const userId = e.user_id;
    const userDataFile = path.join(dataPath, `${userId}.json`);
    
    
    if (!e.msg || typeof e.msg !== 'string') {
        e.reply('未收到有效的改名指令，请输入正确的格式！');
        return;
    }

    const name = e.msg.replace(/^#?yp改名/, '').trim();

    if (!fs.existsSync(userDataFile)) {
        e.reply('你还没有牛牛，请先生成牛牛！');
        return;
    }

    if (!name) {
        e.reply('名字不能为空，请输入有效的名字！');
        return;
    }

    const data = JSON.parse(fs.readFileSync(userDataFile));
    data.name = name;
    fs.writeFileSync(userDataFile, JSON.stringify(data));

    e.reply(`你的牛牛名字已成功更改为：${name}`);
}


 
  async getNickname(userId) {
    const userDataFile = path.join(dataPath, `${userId}.json`);
    if (fs.existsSync(userDataFile)) {
      const data = JSON.parse(fs.readFileSync(userDataFile));
      return data.name || '未设置名称';  
    } else {
      return '未设置名称';
    }
  }

  
  getMentionedInfo() {
    const mention = this.e.message.find(msg => msg.type === 'at');
    return mention ? mention.qq : null;
  }
}






